<?php
$act=$_REQUEST['action'];
$charset=$_REQUEST['charset'];
$str=$_REQUEST['str'];

if($act=='encode')
{
   if($charset=='gb2312')
	{
      $str=iconv("UTF-8","GB2312//IGNORE",$str);
    } 
   echo urlencode($str);
}

if($act=='decode')
{
    $str=urldecode($str);
    if(is_gb2312($str))
	{
        //$str=iconv("GB2312//IGNORE","UTF-8",$str);
		$str=mb_convert_encoding($str,"UTF-8","GBK");
    } 
	echo $str;
}

if($act=='md5'){
  echo md5($str);
}


function is_utf8($string) {
    return preg_match('%^(?:
    [\x09\x0A\x0D\x20-\x7E] # ASCII
    | [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
    | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
    | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
    | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
    | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
    | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
    | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
    )*$%xs', $string);
}
 
function is_gb2312($str)
{
    for($i=0; $i<strlen($str); $i++) {
        $v = ord( $str[$i] );
        if( $v > 127) {
            if( ($v >= 228) && ($v <= 233) )
            {
                if( ($i+2) >= (strlen($str) - 1)) return true;
                $v1 = ord( $str[$i+1] );
                $v2 = ord( $str[$i+2] );
                if( ($v1 >= 128) && ($v1 <=191) && ($v2 >=128) && ($v2 <= 191) ) 
                    return false;
                else
                    return true;
            }
        }
    }
    return true;
}
?>
